var player;
var fps;
var viewport;
var tile_map;
var sprite_sheet;
var world;

var background1;
var background2;
var blocks;

var mapa_json;

var live_info;

function myGame() {
  /* Called once when a game state is activated. Use it for one-time setup code. */
  this.setup = function() {
	
	//carregas definicoes do mapa
	$.ajax({
        url: "mapa/mapa.json",
        dataType: "json",
        async: false,
        success: function(data){
        	mapa_json = data;
        }
	});
	  
    live_info = document.getElementById("live_info");
    
    //instancia do tileset para pegar as partes das imagens
    sprite_sheet = new jaws.SpriteSheet({
    	image: "mapa/tileset-platformer.png", 
    	frame_size: [mapa_json.tilewidth, 
    	             mapa_json.tileheight],
    	orientation: "right"
    });
    
    world = new jaws.Rect(
		0,
		0,
		mapa_json.tilewidth * mapa_json.width,
		mapa_json.tileheight * mapa_json.height
    );
    
    carregarTiles();
    
    //valores do mapa apartir dos valores recebidos por ajax
    tile_map = new jaws.TileMap({
		size: [mapa_json.width, mapa_json.height], 
		cell_size: [mapa_json.tilewidth, mapa_json.tileheight]
    });
    
    tile_map.push(blocks);
    
    viewport = new jaws.Viewport({
    	max_x: world.width, 
    	max_y: world.height
    });

    player = new jaws.Sprite({
    	x:110, 
    	y:320, 
    	scale: 2, 
    	anchor: "center_bottom"
    });

    player.move = function() {
      this.x += this.vx;
      if(tile_map.atRect(player.rect()).length > 0) { 
        this.x -= this.vx;
      }
      this.vx = 0;

      this.y += this.vy;
      var block = tile_map.atRect(player.rect())[0];
      if(block) { 
        // Heading downwards
        if(this.vy > 0) { 
          this.can_jump = true;
          this.y = block.rect().y - 1;
        }
        // Heading upwards (jumping)
        else if(this.vy < 0) {
          this.y = block.rect().bottom + this.height;
        }
        this.vy = 0;
      }
    };

    var anim = new jaws.Animation({sprite_sheet: "droid_11x15.png", frame_size: [11,15], frame_duration: 100});
    player.anim_default = anim.slice(0,5);
    player.anim_up = anim.slice(6,8);
    player.anim_down = anim.slice(8,10);
    player.anim_left = anim.slice(10,12);
    player.anim_right = anim.slice(12,14);
    player.vx = player.vy = 0;
    player.can_jump = true;

    player.setImage( player.anim_default.next() );
    jaws.preventDefaultKeys(["up", "down", "left", "right", "space"]);
  };

  /* update() will get called each game tick with your specified FPS. Put game logic here. */
  this.update = function() {
    player.setImage( player.anim_default.next() );

    player.vx = 0;
    if(jaws.pressed("left"))  { 
    	player.vx = -3; 
    	player.setImage(player.anim_left.next()); 
    }
    if(jaws.pressed("right")) { 
    	player.vx = 3;  
    	player.setImage(player.anim_right.next()); 
    }
    if(jaws.pressed("up"))    { 
    	if(player.can_jump) { 
    		player.vy = -11; 
    		player.can_jump = false; 
    	} 
    }

    // some gravity
    player.vy += 0.4;

    // apply vx / vy (x velocity / y velocity), check for collision detection in the process.
    player.move();

    // Tries to center viewport around player.x / player.y.
    // It won't go outside of 0 or outside of our previously specified max_x, max_y values.
    viewport.centerAround(player);

    live_info.innerHTML = jaws.game_loop.fps + " fps. Player: " + parseInt(player.x) + "/" + parseInt(player.y) + ". ";
    live_info.innerHTML += "Viewport: " + parseInt(viewport.x) + "/" + parseInt(viewport.y) + ".";

  };

  /* Directly after each update draw() will be called. Put all your on-screen operations here. */
  this.draw = function() {
    jaws.clear();

    // the viewport magic. wrap all draw()-calls inside viewport.apply and it will draw those relative to the viewport.
    viewport.apply( function() {
    	background2.draw();
    	background1.draw();
	    blocks.draw();
	    player.draw();
	    
	    
	    //desenhar barra de life
	    jaws.context.lineWidth = 1;
	    jaws.context.fillStyle = "green";
	    
	    jaws.context.font = "12px Helvetica";
	    jaws.context.fillText("MudaFuck", player.x - 15,player.y - 55);
	    
	    jaws.context.fillRect(player.x - 15,player.y - 50,16,7);
	    
	    jaws.context.strokeStyle = "black";
	    jaws.context.strokeRect(player.x - 15,player.y -50,32,7); 
	    
    });
  };
}

jaws.onload = function() {
  jaws.unpack();
  jaws.assets.add(["droid_11x15.png","block.bmp","mapa/tileset-platformer.png"]);
  jaws.start(myGame); // Our convenience function jaws.start() will load assets, call setup and loop update/draw in 60 FPS
};


function carregarFundo(){
	
//	/background.push( new Sprite({image: sprite_sheet.frames[11], x: getX(4), y: getY(4)}) );
}

function carregarTiles(){
	blocks = new jaws.SpriteList();
	background1 = new jaws.SpriteList();
	background2 = new jaws.SpriteList();
    
	var layers = mapa_json.layers;
	
	for ( var int = 0; int < layers.length; int++) {
		
		var data = layers[int].data;
		
		if(layers[int].name=="block"){
			var i = data.length - 1;
			for (var y = 1; y <= mapa_json.height; y++) {
				for (var x = 1; x <= mapa_json.width; x++) {
				
					if(data[i]!=0){
						blocks.push(new Sprite({
							image: sprite_sheet.frames[data[i]-1],
							x: world.width - (x * mapa_json.tilewidth),
							y: world.height - (y * mapa_json.tileheight)
						}));
					}
					i--;
				}
			}
		}
		
		
		if(layers[int].name=="background1"){
			var i = data.length - 1;
			for (var y = 1; y <= mapa_json.height; y++) {
				for (var x = 1; x <= mapa_json.width; x++) {
				
					if(data[i]!=0){
						background1.push(new Sprite({
							image: sprite_sheet.frames[data[i]-1],
							x: world.width - (x * mapa_json.tilewidth),
							y: world.height - (y * mapa_json.tileheight)
						}));
					}
					i--;
				}
			}
		}
		
		
		if(layers[int].name=="background2"){
			var i = data.length - 1;
			for (var y = 1; y <= mapa_json.height; y++) {
				for (var x = 1; x <= mapa_json.width; x++) {
				
					if(data[i]!=0){
						background2.push(new Sprite({
							image: sprite_sheet.frames[data[i]-1],
							x: world.width - (x * mapa_json.tilewidth),
							y: world.height - (y * mapa_json.tileheight)
						}));
					}
					i--;
				}
			}
		}
	}
	
	
	
	    
}

function log(text){
	$("#game-log").append(text);
	$("#game-log").append("<br/>");
}

function getX(tile){
	return tile * mapa_json.tilewidth;
}

function getY(tile){
	return world.height - (tile * mapa_json.tileheight);
}